package com.binguo.wxapi.wxpay;

import com.binguo.common.paymodel.WXResponse;
import com.binguo.common.util.LoggerUtil;
import com.binguo.model.mapper.WxPayOrderMapper;
import com.binguo.model.model.WxPayOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Service
public class WxPayServiceNew {

    @Resource
    private WxPayOrderMapper wxPayOrderMapper;

    @Autowired
    private WXServerPayService wxServerPayService;

    public String notice(String content) {
        return wxServerPayService.notify(content);
    }


    /**
     * 支付预订单，返回可调起微信支付的相关参数
     * @param openId
     * @param orderNo 订单号
     * @param totalAmount 总支付金额
     * @param attach 商品名称
     * @param ipAddress 用户端ip地址
     * @param notifyUrl url
     * @param subMchId 子商户号
     * @param subAppid 子公众号
     * @return
     */
    public WXResponse wxpay(String openId, String orderNo, String totalAmount, String attach, String ipAddress,
                            String appid, String notifyUrl, String subMchId, String subAppid) {

        if (appid == null) {
            appid = WXServerPayService.sub_appid;
        }
        WxPayOrder payOrder = new WxPayOrder();
        payOrder.setOrderNo(orderNo);
        payOrder.setCreateTime(new Date());
        payOrder.setNotifyUrl(notifyUrl);

        wxPayOrderMapper.insertSelective(payOrder);

        WXResponse wxResponse = new WXResponse();

        String prepay_id = wxServerPayService.unifiedOrder(openId, orderNo,
                Long.valueOf(totalAmount), ipAddress, subMchId, subAppid, attach);

        if (prepay_id == null) {
            return null;
        }
        wxResponse.setPrepayId(prepay_id);

        String timestamp = System.currentTimeMillis()/1000 + "";
        wxResponse.setTimeStamp(timestamp);

        //paySign =
        // MD5(appId=wxd678efh567hg6787
        // &nonceStr=5K8264ILTKCH16CQ2502SI8ZNMTM67VS
        // &package=prepay_id=wx2017033010242291fcfe0db70013231072
        // &signType=MD5
        // &timeStamp=1490840662
        // &key=qazwsxedcrfvtgbyhnujmikolp111111) = 22D9B4E54AB1950F51E0649E8810ACD6

        String _package = "prepay_id=" + prepay_id;
        wxResponse.set_package(_package);

        String s = "appId=" + appid + "&nonceStr=Wm3WZYTPz0wzccnW&package="
                + _package + "&signType=MD5&timeStamp=" + timestamp + "&key=" + WXServerPayService.appKey;

        LoggerUtil.console.info("paySignStr = " + s);
        String sign = MD5Util.MD5Upper32(s);
        LoggerUtil.console.info("paySign=" + sign);
        wxResponse.setPaySign(sign);
        wxResponse.setNonceStr("Wm3WZYTPz0wzccnW");
        wxResponse.setSignType("MD5");

        return wxResponse;
    }

}
